/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.query.filter;

import java.sql.PreparedStatement;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;

import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.Clazz;
import com.koylu.caffein.model.clazz.Column;

public class Lt extends Filter {

	private Column column;
	private String alias;
	private String path;
	private Object value;
	private StringBuffer query = null;
	
	public Lt() {}

	public Lt(String alias, String path, Object value) {
		this.alias = alias;
		this.path = path;
		this.value = value;
	}
	
	public String getAlias() {
		return alias;
	}

	public void setAlias(String alias) {
		this.alias = alias;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}
	
	public StringBuffer toQuery(CaffeinConfig caffeinConfig, Map<String, Clazz> aliasMap) throws Exception {
		if(query == null){
			if (column == null) {
				if(aliasMap.containsKey(alias)){
					column = aliasMap.get(alias).pathToColumn(caffeinConfig, path);
					if(column == null){
						throw new RuntimeException("invalid clazz path:"+path);
					}
				}else{
					throw new RuntimeException("invalid clazz alias:"+alias);
				}
			}
			query = new StringBuffer(alias).append(".").append(column.getColumn()).append(" < ").append("?");
		}
		return query;
	}
	
	public int fieldToColumn(CaffeinConfig caffeinConfig, PreparedStatement preparedStatement, int index) throws Exception{
		column.getConverter(caffeinConfig).fieldToColumn(preparedStatement, value, false, index);
		return index + 1;
	}
	
	public void resolveValue(Object object) throws Exception {
		if(value != null){
			String token = getToken(value.toString());
			if(token != null){
				Object realValue = null;
				try {
					realValue = PropertyUtils.getNestedProperty(object, token);
				} catch (Exception e) {}
				setValue(realValue);
			}
		}
	}
}